package com.dayuanit.dy17.oauth.autoconfig.wxloginspringbootstarter.autconfig;

import com.alibaba.fastjson.JSON;
import com.dayuanit.dy17.oauth.autoconfig.wxloginspringbootstarter.util.ApiConnector;

public class WxLoginHandler {

    private String wxLoginUrl;

    private String appId;

    private String redirectUrl;

    private String wxAccessTokenUrl;

    private String secret;

    private String wxUserInfoUrl;

    //第一步：生成请求code的URL地址
    public String getCodeUrl() {
        StringBuilder sx = new StringBuilder();
        sx.append(wxLoginUrl).append("?")
                .append("appid=").append(appId).append("&")
                .append("redirect_uri=").append(redirectUrl).append("&")
                .append("response_type=code").append("&")
                .append("scope=snsapi_login");
        return sx.toString();
    }

    //第二步：根据code获取accessToken
    public WxAccessTokenDomain getAccessToken(String code) {
        StringBuilder sx = new StringBuilder();
        sx.append(wxAccessTokenUrl).append("?")
                .append("appid=").append(appId).append("&")
                .append("secret=").append(secret).append("&")
                .append("code=").append(code).append("&")
                .append("grant_type=authorization_code");

        String result = ApiConnector.get(sx.toString());
        System.out.println("access result=" + result);

        return JSON.parseObject(result, WxAccessTokenDomain.class);
    }

    //第三步：根据accessToken获取用户信息
    public WxUserInfoDomain getWxUserInfo(WxAccessTokenDomain wxAccessTokenDomain) {
        StringBuilder sx = new StringBuilder();
        sx.append(wxUserInfoUrl).append("?")
                .append("access_token=").append(wxAccessTokenDomain.getAccessToken()).append("&")
                .append("openid=").append(wxAccessTokenDomain.getOpenid());

        String result = ApiConnector.get(sx.toString());
        System.out.println("wxuserInfo=" + result);

        return JSON.parseObject(result, WxUserInfoDomain.class);
    }

    public void setWxLoginUrl(String wxLoginUrl) {
        this.wxLoginUrl = wxLoginUrl;
    }

    public void setAppId(String appId) {
        this.appId = appId;
    }

    public void setRedirectUrl(String redirectUrl) {
        this.redirectUrl = redirectUrl;
    }

    public void setWxAccessTokenUrl(String wxAccessTokenUrl) {
        this.wxAccessTokenUrl = wxAccessTokenUrl;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public void setWxUserInfoUrl(String wxUserInfoUrl) {
        this.wxUserInfoUrl = wxUserInfoUrl;
    }
}
